<template>
    <div>
        <BasicDialogVue :data="dialog" @close="onCloseDialog(formRef)">
            <template #content>
                <el-form :model="formData" label-width="110px" :rules="rules" ref="formRef">
                    <el-form-item label="用户名" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入用户名" />
                    </el-form-item>
                    <el-form-item label="登录账号" prop="phone">
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            content="账号必须是字母或数字组成"
                            placement="bottom"
                        >
                            <el-input v-model="formData.phone" type="text" placeholder="请输入登录账号" />
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="登录密码" prop="password" v-if="dialog.type === 'create'">
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            content="密码由字母、数字、特殊符号(._~!@#$%^&*)组成长度为8-20位"
                            placement="bottom"
                        >
                            <el-input v-model="formData.password" placeholder="请输入登录密码" />
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="用户类型">
                        <el-radio-group v-model="formData.userType">
                            <el-radio :label="item.value" v-for="item in userType" :key="item.label">{{
                                item.label
                            }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="用户状态">
                        <el-switch v-model="formData.status" inline-prompt active-text="启用" inactive-text="禁用" />
                    </el-form-item>
                </el-form>

                <div class="btn">
                    <el-button @click="onCloseDialog(formRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                </div>
            </template>
        </BasicDialogVue>
    </div>
</template>
<script setup lang="ts">
import BasicDialogVue from '@/components/baseDialog/Index.vue'
import { ref, reactive, watchEffect } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { createUser, updateUser, userOperation } from '@/apis/company/user'
import { checkPassword_2, regMobile } from '@/utils'
import { DICT_DATA } from '@/utils/dict-data'
const props = defineProps(['data'])
const emit = defineEmits(['close'])
const formRef = ref()
const dialog = reactive({
    visible: false,
    title: '新增用户',
    width: '420px',
    id: '',
    type: 'create'
})

const userType = reactive([...DICT_DATA.get('userType')])

//是否提交
let resubmit = false

const formData = reactive({
    name: '',
    phone: '',
    password: '',
    userType: '1',
    status: true
})
// 手机号码验证
const validatePhonePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入登录账号'))
    } else {
        const pattern = /^[A-Za-z0-9]+$/
        if (pattern.test(formData.phone)) {
            callback()
        } else {
            callback(new Error('格式格式不符合要求'))
        }
    }
}

// 密码验证
const validatePassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入登录密码'))
    } else {
        if (checkPassword_2(formData.password)) {
            callback()
        } else {
            callback(new Error('密码格式不符合要求'))
        }
    }
}

//校验输入
const rules = reactive({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    phone: [{ required: true, validator: validatePhonePass, trigger: 'blur' }],
    password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
})

watchEffect(() => {
    dialog.visible = props.data.visible
    if (props.data.type === 'edit') {
        dialog.title = '编辑用户'
        dialog.type = 'edit'
        dialog.id = props.data.id
        formData.name = props.data.name
        formData.phone = props.data.account
        formData.userType = props.data.userType + ''
        console.log('props.data', props.data)
    } else if (props.data.type === 'create') {
        dialog.title = '新增用户'
        dialog.type = 'create'
        formData.name = ''
        formData.phone = ''
        formData.password = ''
        formData.userType = '1'
    }
})

//监听关闭
const onCloseDialog = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    emit('close')
}
//监听提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', formData)
            if (resubmit) {
                return
            }

            resubmit = true
            const params: userOperation = {
                name: formData.name,
                account: formData.phone,
                disable: formData.status ? 0 : 1,
                userType: Number(formData.userType)
            }
            if (dialog.type === 'create') {
                params.password = formData.password
                createUser(params).then(
                    res => {
                        resubmit = false
                        if (Number(res.data.code) === 200) {
                            formEl.resetFields()
                            emit('close')
                            ElMessage.success('新增成功')
                        }
                    },
                    () => {
                        resubmit = false
                    }
                )
            } else if (dialog.type === 'edit') {
                params.id = dialog.id
                updateUser(params).then(
                    res => {
                        resubmit = false
                        if (Number(res.data.code) === 200) {
                            formEl.resetFields()
                            emit('close')
                            ElMessage.success('修改成功')
                        }
                    },
                    () => {
                        resubmit = false
                    }
                )
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style scoped lang="scss">
.btn {
    display: flex;
    justify-content: center;
    margin: 40px 0 16px 0;
}
</style>
